package com.liuliu.mall.product.service.impl;

import com.liuliu.mall.product.entity.AttrEntity;
import com.liuliu.mall.product.entity.CategoryEntity;
import com.liuliu.mall.product.service.AttrService;
import com.liuliu.mall.product.service.CategoryService;
import com.liuliu.mall.product.vo.AttrGroupWithAttrsVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liuliu.mall.common.utils.PageUtils;
import com.liuliu.mall.common.utils.Query;

import com.liuliu.mall.product.dao.AttrGroupDao;
import com.liuliu.mall.product.entity.AttrGroupEntity;
import com.liuliu.mall.product.service.AttrGroupService;
import org.springframework.util.StringUtils;

@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {

    @Autowired
    CategoryService categoryService;

    @Autowired
    AttrService attrService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                new QueryWrapper<AttrGroupEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查询列表数据
     * 根据列表编号来查询
     *
     * @param params
     * @param catelogId 如何catelogId为0 就不根据catelogId来查询
     * @return
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params, Long catelogId) {
        // 获取检索的关键字
        String key = (String) params.get("key");
        QueryWrapper<AttrGroupEntity> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(key)) {
            // 拼接查询的条件
            wrapper.and((obj) -> {
                obj.eq("attr_group_id", key).or().like("attr_group_name", key);
            });
        }

        if (catelogId == 0) {
            // 不根据catelogId来查询
            IPage<AttrGroupEntity> page = this.page(
                    new Query<AttrGroupEntity>().getPage(params), wrapper
            );

            // 根据分类id获得名称
            getCategoryNameById(page);
            return new PageUtils(page);
        }
        // 根据类别编号来查询属性信息
        wrapper.eq("catelog_id", catelogId);
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params), wrapper
        );

        // 根据分类id获得名称
        getCategoryNameById(page);

        return new PageUtils(page);
    }

    @Override
    public List<AttrGroupWithAttrsVO> getAttrgroupWithAttrsByCatelogId(Long catelogId) {
        List<AttrGroupEntity> attrGroups = this.list(new QueryWrapper<AttrGroupEntity>()
                .eq("catelog_id", catelogId));
        List<AttrGroupWithAttrsVO> list = attrGroups.stream().map((group) -> {
            AttrGroupWithAttrsVO vo = new AttrGroupWithAttrsVO();
            BeanUtils.copyProperties(group, vo);
            List<AttrEntity> attrs = attrService.getRelationAttr(group.getAttrGroupId());
            vo.setAttrs(attrs);
            return vo;
        }).collect(Collectors.toList());
        return list;
    }


    private void getCategoryNameById(IPage<AttrGroupEntity> page) {
        // 缓存已经存在的分类ID与分类名称，避免重复查询相同的数据
        Map<Long, String> categoryMap = new HashMap<>();
        List<AttrGroupEntity> records = page.getRecords();

        records.stream().map((record) -> {
            if (!categoryMap.containsKey(record.getCatelogId())) {
                // 不存在缓存中再从数据库中查询
                CategoryEntity categoryEntity = categoryService.getById(record.getCatelogId());
                if (categoryEntity != null) {
                    record.setCatelogName(categoryEntity.getName());
                    // 查询后保存在缓存中
                    categoryMap.put(record.getCatelogId(), categoryEntity.getName());
                }
            } else {
                // 存在则直接从缓存中获取
                record.setCatelogName(categoryMap.get(record.getCatelogId()));
            }
            return record;
        }).collect(Collectors.toList());
    }

}